// pages/share/share.js
const util = require('../../utils/util.js');
const getCurrentPageUrlWithArgs = require('../../utils/util.js').getCurrentPageUrlWithArgs;
const pages = getCurrentPages();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    width: '',
    height: '',
    screenWidth: '',
    screenHeight: '',
    pixelRatio: '',
    prurl: '',
    temp: [],
    offset: 0,
    popShow: false,
    hidden: true,
    erweima: '',
    lessonid:1
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //获取当前设备的width,height
    let that = this;
    let lesson_id = 1;
    wx.getSystemInfo({
      success: function(res) {
        console.log(res)
        that.setData({
          width: res.windowWidth,
          height: res.windowHeight,
          screenWidth: res.screenWidth,
          screenHeight: res.screenHeight,
          pixelRatio: res.pixelRatio,
          offset: (res.windowWidth - 300) / 2
        })
      },
    })
    this.getCanvas()
  },
  //当有banner图的时候
  getCanvas() {
    let that = this
    let promise1 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: 'http://p8pho5rm4.bkt.clouddn.com/shareimg1.png',
        success: function(res) {
          resolve(res)
        }
      })
    });
    //获取banner的框
    let promise2 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: 'http://p8pho5rm4.bkt.clouddn.com/share.png',
        success: function(res) {
          resolve(res);
        }
      })
    });
    //获取banner图
    let promise3 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: 'http://p8pho5rm4.bkt.clouddn.com/miduo.png',
        success: function(res) {
          resolve(res);
        }
      })
    });
    //分享二维码
    let promise4 = new Promise(function (resolve, reject) {
      if (wx.getStorageSync('erweima') && wx.getStorageSync('lessonid') === that.data.lessonid) {
        wx.getImageInfo({
          src: wx.getStorageSync('erweima'),
          success: function (res) {
            resolve(res);
          }
        })
      } else {
        util.request('wxqcode/getqrcode', { lesson_id: that.data.lessonid, code_type:'wxcode' }, 'POST').then(function (res) {
          console.log(res)
          if (res.errno === 0 && res.data.code === 1) {
            wx.setStorageSync('erweima', res.data.data)
            wx.setStorageSync('lessonid', that.data.lessonid)
            wx.getImageInfo({
              src: res.data.data,
              success: function (res) {
                resolve(res);
              }
            })
          }
        });
      }
    });
    Promise.all([
      promise1, promise2, promise3,promise4
    ]).then(res => {
      const ctx = wx.createCanvasContext('shareImg')
      //获取背景图
      ctx.drawImage(res[0].path, 0, 0, 343, 473)
      //获取背景框
      ctx.drawImage(res[1].path, 11, 55, 322, 181)
      //获取banner
      ctx.drawImage(res[2].path, 15, 59, 313, 164);
      //二维码
      ctx.drawImage(res[3].path, 11, 319, 76, 76);
      ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
      ctx.fillStyle = "#fff";
      ctx.setFontSize(14)
      ctx.fillText("如果你还无法简洁的描述她！", 11, 265);
      ctx.fillText("@吴亦凡", 92, 342);
      ctx.fillText("推荐了一堂好课", 92, 362);
      ctx.fillText("长按识别小程序码查看课程", 92, 381);
      ctx.draw()
    })
  },
  //当没有banner图的时候
  getCanvas2() {
    let that = this
    //分享背景图
    let promise1 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: 'http://p8pho5rm4.bkt.clouddn.com/shareimg2.png',
        success: function(res) {
          resolve(res)
        }
      })
    });
    //分享二维码
    let promise2 = new Promise(function (resolve, reject) {
      if (wx.getStorageSync('erweima') && wx.getStorageSync('lessonid') === that.data.lessonid) {
        wx.getImageInfo({
          src: wx.getStorageSync('erweima'),
          success: function (res) {
            resolve(res);
          }
        })
      } else {
        util.request('wxqcode/getqcode', { lesson_id: that.data.lessonid }, 'GET').then(function (res) {
          if (res.errno === 0 && res.data.code === 1) {
            wx.setStorageSync('erweima', res.data.data)
            wx.setStorageSync('lessonid', that.data.lessonid)
            wx.getImageInfo({
              src: res.data.data,
              success: function (res) {
                resolve(res);
              }
            })
          }
        });
      }
    });
    //获取
    Promise.all([
      promise1, promise2
    ]).then(res => {
      console.log(res)
      const ctx = wx.createCanvasContext('shareImg')
      //获取背景图
      ctx.drawImage(res[0].path, 0, 0, 343, 473)
      //绘制用户头像
      let avatarurl_width = 58; //绘制的头像宽度
      let avatarurl_heigth = 58; //绘制的头像高度
      let avatarurl_x = 40; //绘制的头像在画布上的位置
      let avatarurl_y = 88; //绘制的头像在画布上的位置
      ctx.save();
      ctx.beginPath(); //开始绘制
      //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
      ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
      ctx.clip(); //画好了圆 剪切 原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
      //用户头像
      ctx.drawImage(wx.getStorageSync('userInfo').headurl, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth);
      ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
      ctx.fillStyle = "#262626";
      ctx.setFontSize(12)
      ctx.fillText("昵称", 40, 169);
      ctx.fillText("向您推荐一个很棒的直播间", 40, 187);
      ctx.fillText("如果你还无法简洁的描述她", 40, 205);
      ctx.fillText("长按识别二维码，立即进入课堂", 140, 421);
      //二维码
      ctx.drawImage(res[1].path, 188, 319, 76, 76);
      // ctx.stroke() //画出当前路径的边框
      ctx.draw()
    })
  },
  //canvas转化为图片并预览
  /**
   * 生成分享图
   */
  share: function() {
    var that = this
    wx.showLoading({
      title: '努力生成中...'
    })
    wx.canvasToTempFilePath({
      width: 343,
      height: 473,
      destWidth: 343 * that.data.pixelRatio,
      destHeight: 473 * that.data.pixelRatio,
      canvasId: 'shareImg',
      fileType: 'jpg',
      success: function(res) {
        that.data.temp.push(res.tempFilePath)
        that.setData({
          prurl: res.tempFilePath,
          temp: that.data.temp
        })
        wx.hideLoading()
        that.save()
      },
      fail: function(res) {
        console.log(res)
      }
    })
  },

  /**
   * 保存到相册
   */
  save: function() {
    var that = this
    //生产环境时记得这里要加入获取相册授权的代码
    wx.saveImageToPhotosAlbum({
      filePath: that.data.prurl,
      success(res) {
        wx.showModal({
          content: '图片已保存到系统相册，先预览一下吧~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3',
          success: function(res) {
            if (res.confirm) {
              that.previewImage()
              console.log('用户点击确定');
            }
          }
        })
      }
    })
  },
  previewImage() {
    let that = this
    console.log(that.data.temp[0])
    if (!that.data.temp[0]) return
    wx.previewImage({
      current: '', // 当前显示图片的http链接
      urls: that.data.temp,
      success: function(res) {}
    })
  },
  onShareAppMessage: function (res) {
    var self = this;
    var path = '/pages/share/share';

    return {
      title: '自定义转发标题',
      path: path,
      imageUrl:'http://p8pho5rm4.bkt.clouddn.com/miduo.png?imageMogr2/thumbnail/!50p',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})